/**
 * 
 */
package com.java.test.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.test.timer.MessagePushTimer;
import com.java.test.user.dto.*;
import com.java.test.user.mapper.*;
import com.java.test.user.service.MemberService;
import com.java.test.util.HttpRestUtil;
import com.java.test.util.JsonUtil;
import com.java.test.util.PageInfo;
import com.java.test.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author Administrator
 *
 */
@Service
@Transactional
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberInfoMapper memberInfoMapper;

	@Autowired
	private MemberGradeMapper memberGradeMapper;

	@Autowired
	private MemberSliceMapper memberSliceMapper;

	@Autowired
	private BlackIpMapper blackIpMapper;

	@Autowired
	private IpcheckInfomMapper ipcheckInfomMapper;

	@Autowired
	private BankAccountMapper bankAccountMapper;

	@Autowired
	private PlayAccountMapper playAccountMapper;

	@Autowired
	private AcountResetMapper acountResetMapper;

	@Autowired
	private BehaviorMapper behaviorMapper;

	@Autowired
	private DepositMapper depositMapper;

	@Autowired
	private ReflectMapper reflectMapper;

	@Autowired
	private RunWaterMapper runWaterMapper;

	@Autowired
	DrawingChannelMapper drawingChannelMapper;

	@Autowired
	HttpRestUtil http;

	@Autowired
	RestTemplate client;

	@Value("${get.game.onlineuser.url}")
	private String onlineuserUrl;

	@Value("${get.user.havior.url}")
	private String behaviorUrl;

	@Value("${get.jiaoyiliushui.url}")
	private String orderinfoUrl;

	@Autowired
	private RedisUtil redisUtil;

	public List<MemberInfo> selectMemberList(MemberInfo info) {
		return memberInfoMapper.selectMemberList(info);
	}

	public List<MemberSliceInfo> selectMemberSliceList() {

		return memberSliceMapper.selectMemberSliceList();
	}

	public List<MemberGradeInfo> selectMemberGradeList() {
		return memberGradeMapper.selectMemberGradeList();
	}

	/**
	 * 会员等级排序查询
	 * 
	 * @author
	 * @date 2020/7/28 0028 15:51
	 * @return java.util.List<com.java.test.user.dto.MemberGradeInfo>
	 */
	public List<MemberGradeInfo> selectMemberGradeListOrderBy() {
		return memberGradeMapper.selectMemberGradeListOrderBy();
	}

	public int addMemberGrade(MemberGradeInfo info) {
		int i = memberGradeMapper.insertMemberGradeInfo(info);
		return i;
	}

	public int updateMemberGrade(MemberGradeInfo info) {
		int i = memberGradeMapper.updateMemberGradeInfo(info);
		return i;
	}

	public MemberGradeInfo selectMemberGradeInfoById(int id) {
		return memberGradeMapper.selectMemberGradeInfoById(id);
	}

	public PageInfo<BlackIpInfo> selectMemberBlackipList(BlackIpInfo info, PageInfo<BlackIpInfo> page) {
		// 查询总数量
		int total = blackIpMapper.selectBlackIpListCount(info);
		PageInfo<BlackIpInfo> pageInfo = new PageInfo<BlackIpInfo>(page.getCurrentPage(), page.getPageCount(), total);
		List<BlackIpInfo> list = blackIpMapper.selectBlackIpList(info, page);
		if (list != null && list.size() > 0) {
			list.forEach(b -> {
				String ips = b.getIpAddress();
				if (ips == null || "".equals(ips))
					return;
				String str[] = ips.split("~");
				if (str.length < 2) {
					ips = ips.substring(0, ips.length() - 1);
				}
				b.setIpAddress(ips);
			});
		}
		pageInfo.setList(list);
		return pageInfo;
	}

	public int updateBlackStatus(BlackIpInfo info) {
		int i = blackIpMapper.updateBlackStatus(info);
		if (i > 0) {
			MessagePushTimer.ipCLQ.offer("ipCLQPush");
		}
		return i;
	}

	public int deleteBlackIp(int[] ids) {
		int i = blackIpMapper.deleteBlackIp(ids);
		if (i > 0) {
			MessagePushTimer.ipCLQ.offer("ipCLQPush");
		}
		return i;
	}

	public int insertBlackIp(BlackIpInfo info) {
		int i = blackIpMapper.insertBlackIp(info);
		if (i > 0) {
			MessagePushTimer.ipCLQ.offer("ipCLQPush");
		}
		return i;
	}

	public MemberSliceInfo selectById(int id) {
		return memberSliceMapper.selectById(id);
	}

	public int updateMemberSliceById(MemberSliceInfo info) {
		int i = memberSliceMapper.updateMemberSliceById(info);
		if (i > 0) {
			MessagePushTimer.userGradeCLQ.offer("userSlicePush");
		}
		return i;
	}

	public int insertMemberSlice(MemberSliceInfo info) {
		int i = memberSliceMapper.insertMemberSlice(info);
		if (i > 0) {
			MessagePushTimer.userGradeCLQ.offer("userSlicePush");
		}
		return i;
	}

	public PageInfo<BlackIpInfo> selectMemberBlackipList(BlackIpInfo info) {
		return null;
	}

	@Override
	public PageInfo<IpcheckInfo> selectIpCheckByTimeList(IpcheckInfo info, PageInfo<IpcheckInfo> page) {
		// 查询总数量
		int total = ipcheckInfomMapper.selectIpCheckByTimeCount(info);
		PageInfo<IpcheckInfo> pageInfo = new PageInfo<IpcheckInfo>(page.getCurrentPage(), page.getPageCount(), total);
		List<IpcheckInfo> list = ipcheckInfomMapper.selectIpCheckByTimeList(info, page);
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public int updateBlackStatus(IpcheckInfo info) {
		return ipcheckInfomMapper.updateBlackStatus(info);
	}

	@Override
	public PageInfo<BankAccountInfo> selectbankAcountList(BankAccountInfo info, PageInfo<BankAccountInfo> page) {
		// 查询总数量
		int total = bankAccountMapper.selectBankAccountCount(info);
		PageInfo<BankAccountInfo> pageInfo = new PageInfo<BankAccountInfo>(page.getCurrentPage(), page.getPageCount(),
				total);
		List<BankAccountInfo> list = bankAccountMapper.selectBankAccountList(info, page);

		list.forEach(b -> {
			int chanid = b.getDrawingType();
			DrawingChannelInfo bean = new DrawingChannelInfo();
			bean.setId(chanid);
			DrawingChannelInfo teminfo = drawingChannelMapper.selectdrawingchannelInfobyId(bean);
			if (teminfo != null) {
				b.setDrawingTypeName(teminfo.getChannelName());
			}
		});
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public int insertBankAccount(BankAccountInfo info) {
		return bankAccountMapper.insertBankAccount(info);
	}

	@Override
	public int delBankAccount(BankAccountInfo info) {
		return bankAccountMapper.delBankAccount(info);
	}

	@Override
	public int updateBankAccount(BankAccountInfo info) {
		return bankAccountMapper.updateBankAccount(info);
	}

	@Override
	public BankAccountInfo selectbackAcountInfo(BankAccountInfo info) {
		return bankAccountMapper.selectbackAcountInfo(info);
	}

	@Override
	public int updatePlayAccountNotUse(PlayAccountInfo info) {
		return playAccountMapper.updatePlayAccountNotUse(info);
	}

	@Override
	public int updatePlayAccountUse(PlayAccountInfo info) {
		return playAccountMapper.updatePlayAccountUse(info);
	}

	@Override
	public int updatePlayAccountNotUsepl(int[] ids) {
		return playAccountMapper.updatePlayAccountNotUsepl(ids);
	}

	@Override
	public int updatePlayAccountUsepl(int[] ids) {
		return playAccountMapper.updatePlayAccountUsepl(ids);
	}

	@Override
	@Transactional
	public int insertacountReset(List<AcountReset> list) {

		list.forEach(b -> {
			int i = acountResetMapper.insertacountReset(b);
			int j = playAccountMapper.updatePlayCurentAmout(b.getAccountId(), b.getChangAmount(), b.getResetType());
			if (i > 0 && j > 0) {
				Map<String, Object> map = new HashMap<String, Object>(); 	
				map.put("userId", b.getAccountUniqueNo());
				map.put("type", 1);
				int amount  = b.getResetType()==1?b.getChangAmount().intValue():-b.getChangAmount().intValue();
				map.put("pam", amount);
				MessagePushTimer.updateUserInfoList.add(map);
			}
		
		});
		return 1;
	}

	@Override
	public PageInfo<PlayAccountInfo> selectplayAcountList(PlayAccountInfo info, PageInfo<PlayAccountInfo> page) {
		// 查询总数量
		int total = playAccountMapper.selectplayAccountCount(info);
		PageInfo<PlayAccountInfo> pageInfo = new PageInfo<PlayAccountInfo>(page.getCurrentPage(), page.getPageCount(),
				total);
		List<PlayAccountInfo> list = playAccountMapper.selectplayAccountList(info, page);
		pageInfo.setList(list);
		return pageInfo;
	}
	
	
	@Override
	public int updateplayremarks(PlayAccountInfo info) {
		// 查询总数量
		int i=playAccountMapper.updateplayremarks(info);

		return i;
	}

	@Override
	public List<PlayAccountInfo> exportExcel(PlayAccountInfo info) {

		return playAccountMapper.exportExcel(info);
	}

	@Override
	public PageInfo<BehaviorInfo> selectbehaviorInfoList(String game_account, PageInfo<BehaviorInfo> page,
			String startTime, String endTime) {

		/* gamebehaviorList */

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", game_account);
		params.put("pageNum", page.getCurrentPage());
		params.put("pageSize", page.getPageCount());
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		String repage = http.postHttp(params, behaviorUrl);

		JSONObject jsobj = JSONObject.parseObject(repage);
		int total = jsobj.getIntValue("total");

		JSONArray jsarray = jsobj.getJSONArray("list");
		if (jsarray == null) {
			page.setList(new ArrayList<BehaviorInfo>());
			return page;
		}
		List<BehaviorInfo> relist = new ArrayList<BehaviorInfo>();
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < jsarray.size(); i++) {
			JSONObject obj = jsarray.getJSONObject(i);
			BehaviorInfo info = new BehaviorInfo();
			info.setGameAccount(obj.getString("userId"));
			info.setIpAddress(obj.getString("ip"));
			info.setOperTime(LocalDateTime.parse(obj.getString("time"), df));
			info.setBehaviorContent(obj.getString("behavior"));
			relist.add(info);
		}

		page.setTotalCount(total);
		page.setList(relist);

		return page;
	}

	@Override
	public PageInfo<DepositInfo> selectdepositInfoList(PageInfo<DepositInfo> page) {

		int total = depositMapper.selectdepositCount(page.getInfo());
		PageInfo<DepositInfo> pageInfo = new PageInfo<DepositInfo>(page.getCurrentPage(), page.getPageCount(), total);
		List<DepositInfo> list = depositMapper.selectdepositList(page, page.getInfo());
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public PageInfo<ReflectInfo> selectreflectInfoInfoList(PageInfo<ReflectInfo> page) {
		int total = reflectMapper.selectreflectCount(page.getInfo());
		PageInfo<ReflectInfo> pageInfo = new PageInfo<ReflectInfo>(page.getCurrentPage(), page.getPageCount(), total);
		List<ReflectInfo> list = reflectMapper.selectreflectList(page, page.getInfo());
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public PageInfo<RunWaterInfo> selectrunwaterInfoList(PageInfo<RunWaterInfo> page) {
		String game_account = page.getInfo().getGameAccount();
		String startTime = page.getInfo().getStartTime();
		String endTime = page.getInfo().getEndTime();
		int total = runWaterMapper.selectrunwaterCount(game_account, startTime, endTime);
		PageInfo<RunWaterInfo> pageInfo = new PageInfo<RunWaterInfo>(page.getCurrentPage(), page.getPageCount(), total);
		List<RunWaterInfo> list = runWaterMapper.selectrunWaterItemList(game_account, page, startTime, endTime);
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public JSONObject selectallrunwaterInfo(PageInfo<RunWaterInfo> page) {
		String game_account = page.getInfo().getGameAccount();
		String startTime = page.getInfo().getStartTime();
		String endTime = page.getInfo().getEndTime();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", game_account);
		params.put("pageNum", page.getCurrentPage());
		params.put("pageSize", page.getPageCount());
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		params.put("orderId", page.getInfo().getOrderId());
		// 调用接口
		String repage = http.postHttp(params, orderinfoUrl);
		JSONObject jsobj = JSONObject.parseObject(repage);
		return jsobj;
	}

	@Override
	public PlayAccountInfo selectplayaccountbyId(int id) {
		return playAccountMapper.selectplayaccountbyId(id);
	}

	/**
	 * 查询当前会员条数
	 * 
	 * @author
	 * @date 2020/7/23 0023 10:25
	 * @return int
	 */
	@Override
	public int getMemberListSize() {
		return playAccountMapper.getMemberListSize();
	}

	/**
	 * 查询新会员
	 * 
	 * @author
	 * @date 2020/7/23 0023 10:25
	 * @return java.util.List<com.java.test.user.dto.MemberInfo>
	 */
	@Override
	public List<PlayAccountInfo> getMemberListNow() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startTime = sdf.format(new Date());
		return playAccountMapper.getMemberListNow(startTime);
	}

	/**
	 * 查询老会员
	 * 
	 * @author
	 * @date 2020/7/23 0023 10:25
	 * @return java.util.List<com.java.test.user.dto.MemberInfo>
	 */
	@Override
	public List<PlayAccountInfo> getMemberListOld() {
		List<PlayAccountInfo> entityList = new ArrayList<>();
		Map<Object, Object> map = redisUtil.hmget("historyUser");
		if (map == null || map.size() == 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = sdf.format(new Date());
			List<PlayAccountInfo> list1 = playAccountMapper.getMemberListOld(startTime);
			for (PlayAccountInfo obj : list1) {
				entityList.add(obj);
			}
		} else {
			for (Object obj : map.keySet()) {
				try {
					String str = map.get(obj.toString()).toString();
					entityList.add(JsonUtil.json2obj(str, PlayAccountInfo.class));
				} catch (Exception r) {
					r.printStackTrace();
				}

			}
		}
		return entityList;
	}

	@Override
	public PageInfo<PlayAccountInfo> selectonlineuser(PlayAccountInfo info, PageInfo<PlayAccountInfo> page) {

		String str = this.getonlineUser(page, info);

		if (str == null || "".equals(str)) {
			return null;
		}

		JSONObject jsobj = JSONObject.parseObject(str);

		JSONArray jsonarry = jsobj.getJSONObject("data").getJSONArray("list");

		int totalPage = jsobj.getJSONObject("data").getIntValue("total");

		List<PlayAccountInfo> list = JsonUtil.jsonArray2List(jsonarry.toJSONString(), PlayAccountInfo.class);

		page.setTotalCount(totalPage);
		page.setList(list);

		return page;

	}

	public String getonlineUser(PageInfo<PlayAccountInfo> page, PlayAccountInfo info) {
		ResponseEntity<String> responseResultResponseEntity = null;
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("pageNum", String.valueOf(page.getCurrentPage()));
			params.put("pageSize", String.valueOf(page.getPageCount()));

			params.put("account", info.getAccount());
			params.put("accountType", info.getAccountType() == 0 ? "" : info.getAccountType());
			params.put("sliceValue", info.getSliceValue() == 0 ? "" : info.getSliceValue());
			params.put("gradeValue", info.getGradeValue() == 0 ? "" : info.getGradeValue());
			params.put("areaId", info.getAreaId() == 0 ? "" : info.getAreaId());

			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
			// 请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
			headers.setContentType(type);
			HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(params, headers); // 执行HTTP请求

			responseResultResponseEntity = client.postForEntity(onlineuserUrl, objectHttpEntity, String.class);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return responseResultResponseEntity.getBody();
	}

	/**
	 * 查询会员按照名称
	 * 
	 * @param accountName
	 * @author
	 * @date 2020/8/4 0004 14:28
	 * @return java.util.List<com.java.test.user.dto.PlayAccountInfo>
	 */
	@Override
	public PlayAccountInfo getMemberListByAccountName(String accountName) {
		List<PlayAccountInfo> list = playAccountMapper.getMemberListByAccountName(accountName);
		PlayAccountInfo info = new PlayAccountInfo();
		if (list.size() > 0) {
			info = list.get(0);
		}
		return info;

	}

	/**
	 * 查询提款账号
	 * 
	 * @param info
	 * @author
	 * @date 2020/8/5 0005 14:46
	 * @return java.util.List<com.java.test.user.dto.BankAccountInfo>
	 */
	@Override
	public List<BankAccountInfo> selectBankAccountListPush(BankAccountInfo info) {
		List<BankAccountInfo> list = bankAccountMapper.selectBankAccountListPush(info);

		list.forEach(b -> {
			int chanid = b.getDrawingType();
			DrawingChannelInfo bean = new DrawingChannelInfo(); 
			bean.setId(chanid);
			DrawingChannelInfo teminfo = drawingChannelMapper.selectdrawingchannelInfobyId(bean);
			if (teminfo != null) {
				b.setDrawingTypeName(teminfo.getChannelName());
			}
		});
		return list;
	}

	/**        
	 * 修改金额
	 * 
	 * @param amount
	 * @param account
	 * @author
	 * @date 2020/8/6 0006 11:09
	 * @return int
	 */
	public int updateFrozenAmount(Double[] amount, String account) {
		return playAccountMapper.updateFrozenAmountByAccount(amount, account);
	}

}
